package com.songtech.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

public class LoginFilter extends FormAuthenticationFilter{

	Logger logger = Logger.getLogger(LoginFilter.class);
	
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    		return Boolean.FALSE == super.isLoginRequest(request, response);
    }
    
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            throw new IllegalStateException("获取到的token is null 请先登录");
        }
        Subject subject = getSubject(request, response);
        try {
            subject.login(token);
            return onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException e) {
            return onLoginFailure(token.getPrincipal().toString(),token, e, request, response);
        }
    }
    
    
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
       // logger.debug("用户 {} 登陆成功", token.getPrincipal().toString());
        return super.onLoginSuccess(token, subject, request, response);
    }
    
    
    protected boolean onLoginFailure(String userName,AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response){
    	if(e instanceof org.apache.shiro.authc.IncorrectCredentialsException){
    		 request.setAttribute("loginError", "帐号密码错误");
    	}
//    	else if(e instanceof AccountExpiredException) {
//            request.setAttribute("loginError", "帐号已过期");
//        }
//    	else if(e instanceof AccountLockedException) {
//            request.setAttribute("loginError", "帐号已锁定");
//        }
    	else if(e instanceof UnknownAccountException) {
            request.setAttribute("loginError", "帐号已禁用");
        }
      //  logger.debug("用户 {} 登陆失败", userName);
    	return super.onLoginFailure(token, e, request, response);
    }
}
